package com.example.demo.Filter;

import org.slf4j.MDC;

import javax.servlet.*;
import javax.servlet.annotation.WebFilter;
import java.io.IOException;
import java.util.UUID;

/**
 * @author test01
 */
//使用@WebFilter的时候需要在启动类上加@ServletComponentScan
//@WebFilter(asyncSupported = true, filterName = "mdc", urlPatterns = "/*")
public class MdcFilter implements Filter {

    @Override
    public void init(FilterConfig filterConfig) throws ServletException {
        System.out.println("aaaaaaaaaaaaaaaaaaaaa");
    }

    /**
     * @param request
     * @param response
     * @param chain
     * @throws IOException
     * @throws ServletException
     */
    public void doFilter(ServletRequest request, ServletResponse response,
                         FilterChain chain) throws IOException, ServletException {

        MDC.put("request_uuid", UUID.randomUUID().toString());
        System.out.println("log");

        try {
            chain.doFilter(request, response);
        } finally {
            MDC.remove("request_uuid");
        }
    }

    @Override
    public void destroy() {

    }
}
